//
//  MyController.m
//  WebExtractSimpleViewer
//
//  Created by Daniel Braun on 10/03/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "MyController.h"

#import "WCWebExtractSet.h"
#import "WCExtractSetArray.h"
#import "WCWebLoader.h"
#import "DictionaryWrapper.h"

@implementation MyController

- (id) init {
	self = [super init];
	if (self != nil) {
		status=@"no file";
		curPage=0;
		pages=[[NSMutableArray arrayWithCapacity:10]retain];
	}
	return self;
}
- (void) dealloc {
	[pages release];
	[esets release];
	[status release];
	[extracted release];
	[_aextracted release];
	[super dealloc];
}

- (void) awakeFromNib 
{
}


- (void) pageLoadedBy:(NSObject <WCWebLoadProtocol> *)ctrler private:(WCWebExtractSet*)wes
{
	// page reuslt update
	static int renter=0;
	NSAssert(0==renter, @"re entered\n");
	renter++;
	NSData *h=[ctrler dhtml];
	NSAttributedString *as=[[[NSAttributedString alloc] initWithHTML:h
						     documentAttributes:nil]autorelease];
	[self _addPage:as];
	
	
	NSDictionary *exv=[wes processExtractionWithController:ctrler];
	if (![exv count]) goto extraction_done; // no new variables
	
	[self willChangeValueForKey:@"extractedArray"];
	[_aextracted release]; _aextracted=nil;
	
	NSMutableDictionary *md=[NSMutableDictionary dictionaryWithCapacity:[exv count]];
	NSEnumerator *e=[exv keyEnumerator];
	NSString *k;
	while (k=[e nextObject]) {
		id v;
		NSString *nk;
		v=[exv objectForKey:k];
		nk=[NSString stringWithFormat:@"%@.%@", [wes name], k];
		[md setObject:v forKey:nk];
	}
	if (!extracted) extracted=[md retain];
	else [extracted addEntriesFromDictionary:md];
	
	[self didChangeValueForKey:@"extractedArray"];
	
	NSDictionary *bodyv;
extraction_done:
	bodyv=[wes bodyVariables];
	wes=[wes nextExtractSet];
	if (wes) {
		NSString *content=nil;
		NSURL *u=[wes actualUrlOrContent:&content];
		if (!u) {
			[self setStatus:@"done?"];
		} else {
			[loader setUrl:u delegateQuery:nil urlAccess:[wes urlaccess] bodyVariables:bodyv];
			if (content) {
				[loader loadHtml: content andPerform:@selector(pageLoadedBy:private:) 
					  target:self private:wes];
			} else {
				[loader loadPageAndPerform:@selector(pageLoadedBy:private:) 
						target:self private:wes];
			}
		}
	} else {
		[self setStatus:@"done"];
	}
	renter--;
}

- (IBAction) reload:(id) sender
{
	[self setStatus:@"fetching web data.."];
	[loader release];
	loader=[[WCWebLoader alloc]init];
	WCWebExtractSet *wes=[esets objectAtIndex:0];
	[loader setUrl:[wes actualUrl] delegateQuery:nil urlAccess:[wes urlaccess] bodyVariables:nil];
	[loader loadPageAndPerform:@selector(pageLoadedBy:private:) 
			    target:self private:wes];	
}

- (BOOL) dropFile:(NSString *)f
{
	NSLog(@"loading %@\n", f);
	NSData *data=[NSData dataWithContentsOfFile:f];
	NSDictionary *info = [NSKeyedUnarchiver unarchiveObjectWithData:data];
	if (!info) {
		goto badfile;
	}
	[extracted release];
	extracted=nil;
	
	[esets release]; esets=nil;
	
	id esetsa=[info objectForKey:@"esets"];
	if ([esetsa isKindOfClass:[NSNull class]]) {
		return NO;
	} else if ([esetsa isKindOfClass:[WCExtractSetArray class]]) {
		esets=[esetsa retain];
	} else if ([esetsa isKindOfClass:[NSArray class]]) {
		// compatibility with pre-20070407 files
		esets=[[WCExtractSetArray alloc]initWithArray:esetsa];
	} else {
		NSAssert(0, @"bad class for esets");
	}
	
	if (!esets) return NO;
	if ([esets count]<1) goto badfile;
	//extracted=[[esets parsedOtherVariables]retain];
	//[self parseVariables:extracted];
	[self reload:nil];
	
	return YES;
badfile:
	[self setStatus:@"bad file"];
	return NO;
}

- (NSString *) status
{
	return status;
}
- (void) setStatus:(NSString *) s
{
	[status release];
	status=[s retain];
}


- (NSArray *) extractedArray
{
	if (!extracted) return  [NSArray array];
	if (!_aextracted) {
		[extracted addEntriesFromDictionary:[esets parsedUserVariablesWithDictionary:extracted]];
		_aextracted=[[DictionaryWrapper arrayFromDictionary:extracted]retain];
	}
	return _aextracted;
}


- (NSNumber *) curPage
{
	return [NSNumber numberWithInt:curPage];
}
- (void) setCurPage:(NSNumber *)n
{
	[self willChangeValueForKey:@"page"];
	curPage=[n intValue];
	if (curPage<=0) curPage=1;
	if (curPage>[pages count]) {
		curPage=[pages count];
	}
	[self didChangeValueForKey:@"page"];
}
- (NSNumber *) numPages
{
	int numPages=0;
	numPages=[pages count];
	return [NSNumber numberWithInt:numPages];
}

- (void) _addPage: (NSAttributedString *) p
{
	[self willChangeValueForKey:@"numPages"];
	[pages addObject:p];
	[self didChangeValueForKey:@"numPages"];
	if (1==[pages count]) {
		[self setCurPage:[NSNumber numberWithInt:1]];
	}
}

- (NSAttributedString *) page
{
	if (curPage>[pages count]) return nil;
	if (curPage<=0) return nil;
	return [pages objectAtIndex:(curPage-1)];
}

- (void) parseVariables:(NSMutableDictionary *) v
{
}
@end


